<template>
  <h1>{{ msg }}</h1>

  <p>
    Recommended IDE setup:
    <a href="https://code.visualstudio.com/" target="_blank">VSCode</a>
    +
    <a
      href="https://marketplace.visualstudio.com/items?itemName=octref.vetur"
      target="_blank"
    >
      Vetur
    </a>
    or
    <a href="https://github.com/johnsoncodehk/volar" target="_blank">Volar</a>
    (if using
    <code>&lt;script setup&gt;</code>)
  </p>

  <p>See <code>README.md</code> for more information.</p>

  <p>
    <a href="https://vitejs.dev/guide/features.html" target="_blank">
      Vite Docs
    </a>
    |
    <a href="https://v3.vuejs.org/" target="_blank">Vue 3 Docs</a>
  </p>

  <button type="button" @click="counter++">counter is: {{ counter }}</button>
  <p>doubleCounter is: {{ doubleCounter }}</p>
  <p>{{ message }}</p>
  <div ref="box">Hello,Vue3</div>
  <p>
    Edit
    <code>components/HelloWorld.vue</code> to test hot module replacement.
  </p>
  <button @click="isshow = !isshow">控制子组件显示</button>
  <!-- <hr>
  <Child v-if="isshow"/> -->
</template>

<script lang="ts">
import {
  ref,
  defineComponent,
  reactive,
  computed,
  onMounted,
  onUnmounted,
  toRefs,
  watch, // 数据结构之后任然具有响应式
} from "vue";
import Child from './Child.vue'
export default {
  name: "HelloWorld",
  props: {
    msg: {
      type: String,
      required: true,
    },
  },
  components:{Child},
  setup: () => {
    // counter
    const { counter, doubleCounter } = useCounter();
    // other
    const message = ref("some message");

    let isshow = ref(true)

    //
    const box = ref(null);
    // onMounted(()=>{
    //   console.log(box.value)
    // })
    watch(counter, (newVal, oldVal) => {
      const p = box.value;
      p.textContent = `counter change from ${oldVal} to ${newVal}`;
    });
    return { counter, doubleCounter, message, box,isshow };
  },
};
// 方法管理counter相关
function useCounter() {
  const data: any = reactive({
    counter: 1,
    doubleCounter: computed(() => data.counter * 2),
  });
  let timer: number;
  onMounted(() => {
    timer = setInterval(() => {
      data.counter++;
    }, 1000);
  });
  onUnmounted(() => {
    clearInterval(timer);
  });
  return toRefs(data);
}
</script>

<style scoped>
a {
  color: #42b983;
}

label {
  margin: 0 0.5em;
  font-weight: bold;
}

code {
  background-color: #eee;
  padding: 2px 4px;
  border-radius: 4px;
  color: #304455;
}
</style>
